package praktikumid.w09.p4;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;

/**
 * Listener for the "draw oval" button in a separate class
 * in a separate file.
 * @author Ago
 *
 */
public class DrawOvalListener implements ActionListener {

	@Override
	public void actionPerformed(ActionEvent e) {
		System.out.println("clicked");
		// getSource() gives us the component
		// where the event (click in our case) happened
		// (in our case, it's JButton)
		System.out.println(e.getSource());
		JButton b = (JButton) e.getSource();
		// getParent() returns container component
		// here we traverse up to the frame.
		// As you can see, the hierarchy is 
		// (from bottom to top):
		// JButton
		// ButtonPanel
		// JPanel (frame's content pane)
		// LayeredPane
		// RootPane
		// Frame
		MyFrame f = (MyFrame) b.getParent().getParent().getParent().getParent().getParent();
		System.out.println(b.getParent().getParent().getParent().getParent().getParent());
		
		// every component has a method getComponent(x)
		// which returns child component with the index x.
		// The first component added to the container will
		// have index 0, etc. Here we will try to get
		// second element (index 1).
		// NOTE: we should be aware that some get-method
		// might return NULL, in which case we can
		// end up with NullPointerException.
		// It would be wise to use try-catch here or
		// check if the returned value is null:
		// if (x.getParent() == null) ...
		System.out.println(f.getContentPane().getComponent(1));
		DrawPanel dp = (DrawPanel) f.getContentPane().getComponent(1);
		dp.drawOval(100, 100);
		
		// another note: as we were traversing up to the frame,
		// we already had content pane in one point
		// In reality, there's no point to go up to the frame
		// just because we then can go back down to the 
		// content pane.
		// Instead, it would be sufficient:
		// DrawPanwl dp = (DrawPanel) b.getParent().getParent().getComponent(1);
	}

}
